// 全局变量
let chart;
let currentConfig = null;
let currentPage = 1;
let totalPages = 1;
let searchTerm = '';
const pageSize = 10;

// 默认图表配置
const defaultConfig = {
  title: {
    text: '示例图表'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['销量', '利润']
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '销量',
      type: 'bar',
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: '利润',
      type: 'line',
      data: [220, 182, 191, 234, 290, 330, 310]
    }
  ]
};

// DOM元素
const elements = {
  chartContainer: document.getElementById('chartContainer'),
  configEditor: document.getElementById('configEditor'),
  configName: document.getElementById('configName'),
  configDescription: document.getElementById('configDescription'),
  configTags: document.getElementById('configTags'),
  saveBtn: document.getElementById('saveBtn'),
  resetBtn: document.getElementById('resetBtn'),
  editorError: document.getElementById('editorError'),
  configList: document.getElementById('configList'),
  searchInput: document.getElementById('searchInput'),
  searchBtn: document.getElementById('searchBtn'),
  prevPageBtn: document.getElementById('prevPageBtn'),
  nextPageBtn: document.getElementById('nextPageBtn'),
  pageInfo: document.getElementById('pageInfo'),
  deleteModal: new bootstrap.Modal(document.getElementById('deleteModal')),
  confirmDeleteBtn: document.getElementById('confirmDeleteBtn')
};

// 初始化图表
function initChart() {
  chart = echarts.init(elements.chartContainer);
  updateChart(defaultConfig);
  elements.configEditor.value = JSON.stringify(defaultConfig, null, 2);
}

// 更新图表
function updateChart(config) {
  try {
    chart.setOption(config, true);
    elements.editorError.classList.add('d-none');
  } catch (error) {
    elements.editorError.textContent = `图表渲染错误: ${error.message}`;
    elements.editorError.classList.remove('d-none');
  }
}

// 加载配置列表
async function loadConfigs(page = 1, search = '') {
  try {
    let url = `/api/configs?page=${page}&limit=${pageSize}`;
    if (search) {
      url = `/api/configs/search?q=${encodeURIComponent(search)}&page=${page}&limit=${pageSize}`;
    }
    
    const response = await fetch(url);
    const data = await response.json();
    
    if (data.success) {
      renderConfigList(data.data);
      currentPage = page;
      totalPages = Math.ceil(data.meta.total / pageSize);
      updatePagination();
    } else {
      throw new Error(data.message || '加载配置失败');
    }
  } catch (error) {
    console.error('加载配置失败:', error);
    alert('加载配置失败: ' + error.message);
  }
}

// 渲染配置列表
function renderConfigList(configs) {
  elements.configList.innerHTML = '';
  
  if (configs.length === 0) {
    const li = document.createElement('li');
    li.className = 'list-group-item text-center';
    li.textContent = '没有找到配置';
    elements.configList.appendChild(li);
    return;
  }
  
  configs.forEach(config => {
    const li = document.createElement('li');
    li.className = 'list-group-item d-flex justify-content-between align-items-center';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'config-item-content';
    
    const title = document.createElement('h6');
    title.textContent = config.name;
    title.className = 'mb-1';
    
    const description = document.createElement('small');
    description.textContent = config.description || '无描述';
    description.className = 'text-muted';
    
    contentDiv.appendChild(title);
    contentDiv.appendChild(description);
    
    const btnGroup = document.createElement('div');
    btnGroup.className = 'btn-group btn-group-sm';
    
    const loadBtn = document.createElement('button');
    loadBtn.className = 'btn btn-outline-primary';
    loadBtn.textContent = '加载';
    loadBtn.onclick = () => loadConfig(config._id);
    
    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'btn btn-outline-danger';
    deleteBtn.textContent = '删除';
    deleteBtn.onclick = () => showDeleteConfirm(config._id);
    
    btnGroup.appendChild(loadBtn);
    btnGroup.appendChild(deleteBtn);
    
    li.appendChild(contentDiv);
    li.appendChild(btnGroup);
    
    elements.configList.appendChild(li);
  });
}

// 更新分页信息
function updatePagination() {
  elements.pageInfo.textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
  elements.prevPageBtn.disabled = currentPage <= 1;
  elements.nextPageBtn.disabled = currentPage >= totalPages;
}

// 加载单个配置
async function loadConfig(id) {
  try {
    const response = await fetch(`/api/configs/${id}`);
    const data = await response.json();
    
    if (data.success) {
      currentConfig = data.data;
      elements.configName.value = currentConfig.name;
      elements.configDescription.value = currentConfig.description || '';
      elements.configTags.value = (currentConfig.tags || []).join(',');
      elements.configEditor.value = JSON.stringify(currentConfig.config, null, 2);
      updateChart(currentConfig.config);
    } else {
      throw new Error(data.message || '加载配置失败');
    }
  } catch (error) {
    console.error('加载配置失败:', error);
    alert('加载配置失败: ' + error.message);
  }
}

// 保存配置
async function saveConfig() {
  try {
    const configJson = elements.configEditor.value;
    let configObj;
    
    try {
      configObj = JSON.parse(configJson);
    } catch (error) {
      elements.editorError.textContent = `JSON解析错误: ${error.message}`;
      elements.editorError.classList.remove('d-none');
      return;
    }
    
    const name = elements.configName.value.trim();
    if (!name) {
      alert('请输入配置名称');
      return;
    }
    
    const configData = {
      name,
      description: elements.configDescription.value.trim(),
      config: configObj,
      tags: elements.configTags.value ? elements.configTags.value.split(',').map(tag => tag.trim()) : []
    };
    
    let url = '/api/configs';
    let method = 'POST';
    
    if (currentConfig) {
      url = `/api/configs/${currentConfig._id}`;
      method = 'PUT';
    }
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(configData)
    });
    
    const data = await response.json();
    
    if (data.success) {
      alert(currentConfig ? '配置更新成功' : '配置创建成功');
      currentConfig = data.data;
      loadConfigs(currentPage, searchTerm);
    } else {
      throw new Error(data.message || '保存配置失败');
    }
  } catch (error) {
    console.error('保存配置失败:', error);
    alert('保存配置失败: ' + error.message);
  }
}

// 显示删除确认
function showDeleteConfirm(id) {
  elements.confirmDeleteBtn.onclick = () => deleteConfig(id);
  elements.deleteModal.show();
}

// 删除配置
async function deleteConfig(id) {
  try {
    const response = await fetch(`/api/configs/${id}`, {
      method: 'DELETE'
    });
    
    const data = await response.json();
    
    if (data.success) {
      elements.deleteModal.hide();
      alert('配置删除成功');
      
      if (currentConfig && currentConfig._id === id) {
        resetConfig();
      }
      
      loadConfigs(currentPage, searchTerm);
    } else {
      throw new Error(data.message || '删除配置失败');
    }
  } catch (error) {
    console.error('删除配置失败:', error);
    alert('删除配置失败: ' + error.message);
    elements.deleteModal.hide();
  }
}

// 重置配置
function resetConfig() {
  currentConfig = null;
  elements.configName.value = '';
  elements.configDescription.value = '';
  elements.configTags.value = '';
  elements.configEditor.value = JSON.stringify(defaultConfig, null, 2);
  updateChart(defaultConfig);
}

// 搜索配置
function searchConfigs() {
  searchTerm = elements.searchInput.value.trim();
  currentPage = 1;
  loadConfigs(currentPage, searchTerm);
}

// 事件监听
function setupEventListeners() {
  // 编辑器内容变化
  elements.configEditor.addEventListener('input', () => {
    try {
      const configObj = JSON.parse(elements.configEditor.value);
      updateChart(configObj);
      elements.editorError.classList.add('d-none');
    } catch (error) {
      elements.editorError.textContent = `JSON解析错误: ${error.message}`;
      elements.editorError.classList.remove('d-none');
    }
  });
  
  // 保存按钮
  elements.saveBtn.addEventListener('click', saveConfig);
  
  // 重置按钮
  elements.resetBtn.addEventListener('click', resetConfig);
  
  // 搜索按钮
  elements.searchBtn.addEventListener('click', searchConfigs);
  
  // 搜索输入框回车
  elements.searchInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      searchConfigs();
    }
  });
  
  // 分页按钮
  elements.prevPageBtn.addEventListener('click', () => {
    if (currentPage > 1) {
      loadConfigs(currentPage - 1, searchTerm);
    }
  });
  
  elements.nextPageBtn.addEventListener('click', () => {
    if (currentPage < totalPages) {
      loadConfigs(currentPage + 1, searchTerm);
    }
  });
  
  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => {
    if (chart) {
      chart.resize();
    }
  });
}

// 初始化
function init() {
  initChart();
  setupEventListeners();
  loadConfigs();
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);